package com.jwb.pub.controller;

import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jwb.pub.dao.BaseDAO;
import com.jwb.pub.service.DeptService;
import com.jwb.pub.service.UserInfoService;
import com.jwb.util.MainController;
import com.jwb.util.Md5Str;
import com.jwb.util.ToolsUtil;
@Slf4j
@Controller
@RequestMapping(value="/pub/userInfo")
public class UserInfoController extends MainController{


	@Autowired
	private BaseDAO baseDAO;
	@Autowired
	private UserInfoService userInfoService;
	@Autowired
	private DeptService deptService;
	
	
	/**
	 * http://127.0.0.1:8080/ssm/userInfo/getCurUserInfoForSession
	 * @description：通过session 返回用户信息 
	 * @author liuyn
	 * @return	
	 * @createDate 2018-3-15
	 * @createTime 下午5:04:33
	 */
    @RequestMapping(value="/getCurUserInfoForSession")
    @ResponseBody
	public String getCurUserInfoForSession(HttpServletRequest req) throws Exception	{
    	HttpSession session = req.getSession();
    	JSONObject jsobject = new JSONObject();        
    	JSONObject jso = new JSONObject();      
        jsobject.put("respCode", "0");
    	jsobject.put("respDesc", "成功");    	
    	String userId=(String)session.getAttribute("userId")  == null ? "" : (String)session.getAttribute("userId");
    	String userName=(String)session.getAttribute("userName") == null ? "" : (String)session.getAttribute("userName");
    	String realName=(String)session.getAttribute("realName") == null ? "" : (String)session.getAttribute("realName");
    	String contactPhone=(String)session.getAttribute("contactPhone") == null ? "" : (String)session.getAttribute("contactPhone");
    	String curDeptId=(String)session.getAttribute("curDeptId") == null ? "" : (String)session.getAttribute("curDeptId");
    	String curDeptName=(String)session.getAttribute("curDeptName") == null ? "" : (String)session.getAttribute("curDeptName");
    	String curDeptLevel=(String)session.getAttribute("curDeptLevel") == null ? "" : (String)session.getAttribute("curDeptLevel");
    	String operDeptId=(String)session.getAttribute("operDeptId") == null ? "" : (String)session.getAttribute("operDeptId");
    	String operDeptName=(String)session.getAttribute("operDeptName") == null ? "" : (String)session.getAttribute("operDepName");
    	String operDeptLevel=(String)session.getAttribute("operDeptLevel") == null ? "" : (String)session.getAttribute("operDeptLevel");
    	String roleList=(String)session.getAttribute("roleList") == null ? "" : (String)session.getAttribute("roleList");
    	String privNames=(String)session.getAttribute("privNames") == null ? "" : (String)session.getAttribute("privNames");
    	String privDeptId=(String)session.getAttribute("privDeptId") == null ? "" : (String)session.getAttribute("privDeptId");
    	String privDeptName=(String)session.getAttribute("privDeptName") == null ? "" : (String)session.getAttribute("privDeptName");
    	String privDeptLevel=(String)session.getAttribute("privDeptLevel") == null ? "" : (String)session.getAttribute("privDeptLevel");
    	
    	String rank = (String) session.getAttribute("rank") == null ? ""
				: (String) session.getAttribute("rank");
    	String deptCode = (String) session.getAttribute("deptCode") == null ? ""
				: (String) session.getAttribute("deptCode");
		String groupCode = (String) session.getAttribute("groupCode") == null ? ""
				: (String) session.getAttribute("groupCode");
		String rankDeptId = (String) session.getAttribute("rankDeptId") == null ? ""
				: (String) session.getAttribute("rankDeptId");
		String kpperson = (String) session.getAttribute("kpperson") == null ? ""
				: (String) session.getAttribute("kpperson");
		String psrange = (String) session.getAttribute("psrange") == null ? ""
				: (String) session.getAttribute("psrange");
		
    	

    	jso.put("userId",userId);
    	jso.put("userName",userName);
    	jso.put("realName",realName);
    	jso.put("contactPhone",contactPhone);
    	jso.put("curDeptId",curDeptId);
    	jso.put("curDeptName",curDeptName);
    	jso.put("curDeptLevel",curDeptLevel);
    	jso.put("operDeptId",operDeptId);
    	jso.put("operDeptName",operDeptName);
    	jso.put("operDeptLevel",operDeptLevel);
    	jso.put("roleList",roleList);
    	jso.put("privNames",privNames);
    	jso.put("privDeptId",privDeptId);
    	jso.put("privDeptLevel", privDeptLevel);
    	jso.put("privDeptName", privDeptName);
    	jso.put("rank",rank);
    	jso.put("deptCode",deptCode);
    	jso.put("groupCode",groupCode);
    	jso.put("rankDeptId",rankDeptId);
    	jso.put("kpperson",kpperson);
    	jso.put("psrange", psrange);
    	jsobject.put("userinfo",jso);    	
		log.info("getCurUserInfoForSession "+jsobject.toString());		
		return jsobject.toString();
	}
	
   

    
    
    /**
	 * http://127.0.0.1:8080/ssm/userInfo/testPro
	 * @description：通过session 返回用户信息 
	 * @author liuyn
	 * @return	
	 * @createDate 2018-3-15
	 * @createTime 下午5:04:33
	 */
    @RequestMapping(value="/testPro")
    @ResponseBody
	public String testPro(HttpServletRequest req) throws Exception	{    	
    	JSONObject jsobject = new JSONObject();  
		JSONArray jsarry = new JSONArray();
    	JSONObject json = new JSONObject();      	 
    	json.put("name", "刘亚楠");
    	json.put("real_name", "liuyn");
    	jsarry.add(json);
    	json = new JSONObject();
    	json.put("name", "管理员");
    	json.put("real_name", "admin");
    	jsarry.add(json); 
    	json = new JSONObject();
    	json.put("name", "王建");
    	json.put("real_name", "wj");
    	jsarry.add(json);   	
    	json = new JSONObject();
    	json.put("list", jsarry);    	
    	String jsonstr="";
    	jsonstr=json.toJSONString();    	    	
		List<String> pamList = new ArrayList();
		pamList.add(jsonstr);		
		jsobject=baseDAO.excuteProSql("testjson", pamList);
		log.info("testPro-testjson "+jsobject.toString());    	
//    	String jsonstr2="";
//    	jsonstr2=jsarry.toJSONString();    	    	
//		pamList = new ArrayList();
//		pamList.add(jsonstr2);		
//		jsobject=baseDAO.excuteProSql("testjson2", pamList);
//		log.info("testPro-testjson2 "+jsobject.toString());	
		return jsobject.toString();
	}

    @RequestMapping("/userInfoList")
    @ResponseBody
    public String userInfoList(HttpServletRequest req) throws Exception
	{
    	//deptId  currentPageNbr  realName  deptLevel
    	String deptId = req.getParameter("deptId");
    	String deptIds= req.getParameter("deptIds");
    	String currentPageNbr= req.getParameter("currentPageNbr") == null ? "1" : req.getParameter("currentPageNbr");
 	    String pageSize= req.getParameter("pageSize") == null ? "10" : req.getParameter("pageSize");
    	String realName = req.getParameter("realName");
    	if(realName==null) realName="";
    	int deptLevel = Integer.valueOf(req.getParameter("deptLevel"));
    	
    	JSONObject jsobject = new JSONObject();
    	String curDeptId = (String)req.getSession().getAttribute("curDeptId");
    	if (deptId == null || "".equals(deptId)) 		
    		deptId = curDeptId;
    	String privNames = (String)req.getSession().getAttribute("privNames");
    	Properties prop = new Properties();
		ClassPathResource classPathResource = new ClassPathResource("/prop/config.properties");
		String[] props = ToolsUtil.getProp("config.properties","onlyDataLastNode","treeLevel","hasChild");
    	boolean onlyDataLastNode = Boolean.parseBoolean(props[0]);
    	int treeLevel = Integer.valueOf(props[1]);
    	boolean hasChild = Boolean.parseBoolean(props[2]);
    	
//    	this.pageInit();
//    	this.getPage().setEveryPageCnt(10);
    	this.pageInit();
	    this.getPage().setEveryPageCnt(Integer.parseInt(pageSize));    	
	    this.getPage().setCurrentPageNbr(Integer.parseInt(currentPageNbr));	    	
	    	
    	boolean userInfoEditRight =false, userInfoInputRight=false, userInfoAddRight=false;
    	if(privNames.indexOf("user_manage")>=0){
    		userInfoEditRight= true;
    	}
    	if(privNames.indexOf("user_manage")>=0){
    		userInfoInputRight = true;
    	}
    	if(userInfoEditRight){
    		if(onlyDataLastNode&&deptLevel==treeLevel){
    			userInfoAddRight = true;
    		}else if(!onlyDataLastNode){
    			//hasChild true 有没有孩子 都是添加的    false  该部门节点无孩子 不能添加
    			if(hasChild)
    			{
    				userInfoAddRight = true;	
    			}
    			else
    			{
    				//如果有部门下有孩子才能添加
    				//userInfoAddRight = true;
    				//sql语句
    				String sql="select count(*) cnt from dept d where d.dept_parent_id='"+deptId+"' and dept_sts='A' ";
    				int dcnt=baseDAO.findBySqlCnt(sql);
    				if(dcnt==0)
    				{
    					userInfoAddRight = true;
    				}
    				
    			}
    			
    		 
    		
    		}    		
    	}
    
    	jsobject.put("userInfoAdd", deptService.getButtonInfo("添加",userInfoAddRight));
    	jsobject.put("userInfoDel", deptService.getButtonInfo("删除",	userInfoEditRight));
		
    	JSONArray jsarry = new JSONArray();
    	
    	String deptSql = "SELECT dept_parent_id, dept_name from dept where dept_id='"+deptId+"' and dept_sts='A'";
    	JSONObject obj = baseDAO.findBySqlToJosn(deptSql).getJSONArray("list").getJSONObject(0);
    	String deptParentId = obj.getString("dept_parent_id");
    	String deptName = obj.getString("dept_name");
    	
//    	int pageNo =0;
    	
//    	String sql="SELECT count(*) from user_info where cur_dept_id='"+deptId+"' and sts='A' and real_name like '%"+realName+"%'";
//    	int totalRecords = pubDAO.findBySqlCnt(sql);
//    	this.page.setTotalRecords(totalRecords);
//    	if(page.getTotalRecords()>0){
//    		page.formatPage();
//    	}
//    	if(currentPageNbr==null){
//    		currentPageNbr = "1";
//    	}
//    	pageNo = Integer.valueOf(currentPageNbr);
//    	page.setCurrentPageNbr(pageNo);
    	String sql="";
    	sql="SELECT u.user_name userName, u.user_id userId, u.role_list roleList, (select group_concat(role_name) from role where instr(u.role_list,role_id)>0) roleListName, u.real_name realName,u.another_name penName, "
    			+ " u.rmk rmk,u.rmk2 rmk2,u.rmk3 rmk3,u.rank rank, (select code_desc from user_dict where dict_name='rank' and code = u.rank) rankname, u.sex_type sexType, "
    			+ " (select code_desc from user_dict where dict_name='sex' and code = u.sex_type) sexTypeName, u.cur_dept_id  deptId, "
    		//	+" (select dept_name from dept where dept_id = u.cur_dept_id and dept_sts='A') deptName, "
    			
//    		    +"decode((select dept.dept_level "
//    		    +"    from dept"
//	            +"   where dept.dept_id = u.cur_dept_id"
//	           +"      and dept.dept_sts = 'A'),"
//	           +"   '2',"
//	          +"    (select dept_name"
//	         +"        from dept"
//	        +"        where dept_id = u.cur_dept_id "
//	        +"          and dept_sts = 'A'),"
//	       +"       (select dept_name"
//	       +"          from dept"
//	      +"          where dept_id = u.dept_code"
//	      +"            and dept_sts = 'A')||'/'||(select dept_name"
//	     +"            from dept"
//	     +"           where dept_id = u.cur_dept_id"
//	     +"             and dept_sts = 'A')) deptName,"
    			
    		     +"  REPLACE ( getDeptParentNames ( u.cur_dept_id ), ',', '-->' ) deptName,"
    			+ " u.contact_phone contactPhone, u.sts_date stsDate, u.oper_dept_id operDeptId, (select dept_name from dept where dept_id = u.oper_dept_id and dept_sts='A') operDeptName,u.duty_flag dutyFlag,"
    			+ "(select d.code_desc from user_dict d where d.dict_name='duty_flag' and d.sts='A' and d.code=u.duty_flag) dutyFlagName,u.phone phone, "
    			+ " u.task_num taskNum,u.kp_join kpJoin,u.kp_person kpPerson,u.duty_code dutyCode,(select gw.gwmc from khgwpz gw where gw.gwid=u.duty_code and gw.sts='A') dutyCodeName,"
    			+ "u.kp_class kpClass,u.dept_code deptCode,u.group_code groupCode,u.display_order displayOrder, date_format (u.birth,'%Y%m%d') birth, "    			
    			+"   (select dept.dept_level "
    			+"  from dept "
    			+"  where dept.dept_id = u.cur_dept_id "
    			+"    and dept.dept_sts = 'A') dept_level, ps_range,duty_others "    			
    			+ " from user_info u where u.sts='A' and u.cur_dept_id in ("+deptIds+") and u.real_name like '%"+realName+"%' order by cast( u.display_order AS UNSIGNED INT )"; //ToolsUtil.nestDeptSql(deptId, true)
    	//JSONObject jso = pubDAO.findBySqlToJosn(sql, page);
    	JSONObject jso = baseDAO.findBySqlToJosn(sql, this.getPage());
    	JSONArray array = jso.getJSONArray("list");
    	if(jso.getString("respCode").equals("0")&&!array.isEmpty()){
    		
    		for(int i=0;i<array.size();i++){
    			JSONObject uobj = array.getJSONObject(i);
        		JSONObject userInfo = new JSONObject();
        		userInfo.put("userName", uobj.getString("username"));
        		userInfo.put("userId", uobj.getString("userid"));
        		String roleList = uobj.getString("rolelist");
        		if(roleList.length()>=3){
        			roleList = roleList.substring(1, roleList.length() - 1);
        		}
        		userInfo.put("roleList", roleList);
        		userInfo.put("roleListName", uobj.getString("rolelistname"));
        		userInfo.put("realName", uobj.getString("realname"));
        		userInfo.put("penName", uobj.getString("penname"));        		
        		userInfo.put("rank", uobj.getString("rank"));
        		userInfo.put("rankName", uobj.getString("rankname"));
        		userInfo.put("sexType", uobj.getString("sextype"));
        		userInfo.put("sexTypeName", uobj.getString("sextypename"));
        		userInfo.put("deptId", Integer.valueOf(uobj.getString("deptid")));
        		userInfo.put("deptName", uobj.getString("deptname"));
        		userInfo.put("contactPhone", uobj.getString("contactphone"));
        		userInfo.put("stsDate", uobj.getString("stsdate"));
        		userInfo.put("operDeptId", uobj.getString("operdeptid"));
        		userInfo.put("operDeptName", uobj.getString("operdeptname"));
        		userInfo.put("userInfoEdit", deptService.getButtonInfo("编辑", userInfoEditRight));
        		userInfo.put("userInfoDel", deptService.getButtonInfo("删除", userInfoEditRight));
        		userInfo.put("userPwdReset", deptService.getButtonInfo("重置密码", userInfoEditRight));
        		userInfo.put("userInfoInput", deptService.getButtonInfo("完整信息", userInfoInputRight));
        		userInfo.put("dutyFlag", uobj.getString("dutyflag"));
        		userInfo.put("dutyFlagName", uobj.getString("dutyflagname"));
        		userInfo.put("phone", uobj.getString("phone"));
        		userInfo.put("taskNum", uobj.getString("tasknum"));
        		userInfo.put("kpJoin", uobj.getString("kpjoin"));
        		userInfo.put("kpPerson", uobj.getString("kpperson"));
        		userInfo.put("dutyCode", uobj.getString("dutycode"));
        		userInfo.put("dutyOthers", uobj.getString("duty_others"));
        		userInfo.put("dutyCodeName", uobj.getString("dutycodename"));
        		userInfo.put("kpClass", uobj.getString("kpclass"));
        		userInfo.put("deptCode", uobj.getString("deptcode"));
        		userInfo.put("groupCode", uobj.getString("groupcode"));
        		userInfo.put("displayOrder", uobj.getString("displayorder"));
        		userInfo.put("birth", uobj.getString("birth"));
        		userInfo.put("dept_level", uobj.getString("dept_level"));
        		userInfo.put("ps_range", uobj.getString("ps_range"));
        		userInfo.put("rmk", uobj.getString("rmk"));
        		userInfo.put("rmk2", uobj.getString("rmk2"));
        		userInfo.put("rmk3", uobj.getString("rmk3"));
        		jsarry.add(userInfo);
        	}    		
    	
        	jsobject.put("userInfoList", jsarry);
    		jsobject.put("page", page);
    		jsobject.put("deptId", deptId);
    		jsobject.put("deptIdPar", deptParentId);
    		jsobject.put("deptName", deptName);
    		jsobject.put("respCode", "0");
    		jsobject.put("respDesc", "OK");    		
    		
    	}else{
    		jsobject.put("deptId", deptId);
			jsobject.put("deptIdPar", deptParentId);
			jsobject.put("deptName", deptName);
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "没有数据");
    	}
    	log.info("userInfoList "+jsobject.toString());
		
		return jsobject.toString();
	}
    
    @RequestMapping("/deptConfig")
    @ResponseBody
    public String deptConfig(HttpServletRequest req) throws Exception{
    	JSONObject jsobject = new JSONObject();
    	String deptLevel = (req.getParameter("deptLevel")==null?"":req.getParameter("deptLevel"));
    	String deptId = (req.getParameter("deptId")==null?"":req.getParameter("deptId"));
    	
    	String sql = "select dept_change, dept_priv, role_check, role_list from DEPT_CONFIG t where dept_id = '"+deptId+"'";
    	jsobject = baseDAO.findBySqlToJosn(sql);			
    	
    	
    	return jsobject.toString();
    }
    @RequestMapping("/getOptionInfo")
    @ResponseBody
    public String getOptionInfo(HttpServletRequest req){
    	JSONObject jsobject = new JSONObject();
    	String sex="select code, code_desc codedesc from user_dict where dict_name = 'sex' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String rank = "select code, code_desc codedesc from user_dict where dict_name='rank' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String role = "select role_id roleid, role_name rolename from role";
    	String dutyf = "select code dutyvalue, code_desc dutydesc from user_dict where dict_name = 'duty_flag' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String kpj = "select code kpjvalue, code_desc kpjdesc from user_dict where dict_name = 'kp_join' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String kpp = "select code kppvalue, code_desc kppdesc from user_dict where dict_name = 'kp_person' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String jxkp = "select code jxkpvalue, code_desc jxkpdesc from user_dict where dict_name = 'jxkpfl' and sts='A' order by cast(display_order AS UNSIGNED INT)";
    	String roleList = (String)req.getSession().getAttribute("roleList");
    	try {
		
			jsobject.put("sexlist", baseDAO.findBySqlToJosn(sex).getJSONArray("list"));
					
			jsobject.put("ranklist", baseDAO.findBySqlToJosn(rank).getJSONArray("list"));
			
			jsobject.put("rolelist", baseDAO.findBySqlToJosn(role).getJSONArray("list"));
			
			jsobject.put("dutyflist", baseDAO.findBySqlToJosn(dutyf).getJSONArray("list"));
			
			jsobject.put("kpjlist", baseDAO.findBySqlToJosn(kpj).getJSONArray("list"));
				
			jsobject.put("kpplist", baseDAO.findBySqlToJosn(kpp).getJSONArray("list"));
			
			jsobject.put("jxkplist", baseDAO.findBySqlToJosn(jxkp).getJSONArray("list"));
			
			
			
			jsobject.put("respCode", "0");
			jsobject.put("respDesc", "OK");
			
		} catch (Exception e) {
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "系统忙，请稍候再试");
		}  	    	
    	
    	return jsobject.toString();
    }
    @RequestMapping("/userInfoSave")
    @ResponseBody
	public String userInfoSave(HttpServletRequest req) 
	{
		JSONObject jsobject = new JSONObject();
		String userId = req.getParameter("userId");
//		String deptId = req.getParameter("deptId");
		String addDeptId = req.getParameter("addDeptId");
		String operDeptId = req.getParameter("operDeptId");
//		String operDeptId = (String)req.getSession().getAttribute("curDeptId");
		String userName = req.getParameter("userName");
		String realName = req.getParameter("realName");
		String penName = req.getParameter("penName");
		String sexcode = req.getParameter("sexcode");
		String rankcode = req.getParameter("rankcode");
		String roleList = ","+req.getParameter("roleList")+",";
		String deptCode = req.getParameter("addDeptId");   // addDeptId  原deptCode
		String groupCode = req.getParameter("groupCode"); // addDeptId父亲
		String displayOrder = req.getParameter("displayOrder");
		String dutyFlag = req.getParameter("dutyFlag");
		String phone = req.getParameter("phone");
		String kpPerson = req.getParameter("kpPerson");
		String kpJoin = req.getParameter("kpJoin");
		String dutyCode = req.getParameter("dutyCode");
//		String taskNum = req.getParameter("taskNum");
		String kpClass = req.getParameter("kpClass");
		String birth = req.getParameter("birth");
		String backUp = req.getParameter("backUp");
		String range = req.getParameter("range");
		
		String operDeptName =req.getParameter("operDeptName");
		String operCode = (String)req.getSession().getAttribute("userId");
		String dutyOthers =  req.getParameter("dutyOthers") == null ? "" : req
				.getParameter("dutyOthers");
		String saveSql="";
		
		try{
			if("1".equals(dutyFlag)){   //deptCode
				String sql= "SELECT COUNT(*) FROM user_info where dept_Code='"+addDeptId+"' and sts='A' and duty_Flag='1' and user_id <> '"+userId+"' ";
				int cnt = baseDAO.findBySqlCnt(sql);
	    		if(cnt>0){
					jsobject.put("respCode", "1");
					jsobject.put("respDesc", "负责人已存在");
					return jsobject.toString();
				}
			}
			if(!"".equals(addDeptId)&&null!=addDeptId){
				String sql= "select * from DEPT t where dept_id='"+addDeptId+"' and dept_sts='A' ";
				JSONObject jso = baseDAO.findBySqlToJosn(sql);
				if(jso!=null&&jso.getJSONArray("list").size()>0){
					JSONArray array = jso.getJSONArray("list");
					JSONObject obj = array.getJSONObject(0);
					groupCode= obj.getString("dept_parent_id");
				}						
			}
			
			
			String password = Md5Str.str2MD5to16byte(ToolsUtil.getProp("config.properties", "dft_pwd"));
			if("".equals(userId) || null == userId){
				SqlSession session = null;
				Connection conn = null;
				PreparedStatement ps = null;
				PreparedStatement ps2 = null;
				PreparedStatement ps3 = null;
				try{
					session = baseDAO.getSession();
					conn = session.getConnection();
					conn.setAutoCommit(false);
					//userId = String.valueOf(pubDAO.getSeq("userid.nextval"));
					jsobject.put("savetype", "add");
//					saveSql= "insert into user_info "+
//					 " (user_name, password,rank, sts, sts_date, role_list, real_name, another_name,user_id, sex_type,  cur_dept_id, oper_dept_id, "
//					 + " display_order, duty_flag, phone, kp_join, kp_person, duty_code,duty_others, oper_code, oper_date, dept_code, group_code,birth,ps_range )" +  //task_num, kp_class, 
//					 " values "+
//					 " ('"+userName+"','"+password+"','"+rankcode+"', 'C', NOW(), '"+roleList+"', '"+realName+"', '"+penName+"','"+userId+"', '"+sexcode+"', '"+addDeptId+"', '"+operDeptId+"',"
//					 + "'"+displayOrder+"','"+dutyFlag+"','"+phone+"','"+kpJoin+"','"+kpPerson+"','"+dutyCode+"','"+dutyOthers+"','"+operCode+"',NOW(),'"+deptCode+"','"+groupCode+"', STR_TO_DATE('"+birth+"','%Y%m%d'),'"+range+"' )"; //'"+taskNum+"', '"+kpClass+"',
//					ps= conn.prepareStatement(saveSql);	
//					ps.addBatch();
					saveSql= "insert into user_info "+
							 " (user_name, password,rank, sts, sts_date, role_list, real_name,another_name, sex_type,  cur_dept_id, oper_dept_id, "
							 + " display_order, duty_flag, phone,  kp_join, kp_person, duty_code, duty_others, oper_code, oper_date, dept_code, group_code,birth,ps_range )" + //task_num, kp_class,
							 " values "+
							 " ('"+userName+"','"+password+"','"+rankcode+"', 'A', NOW(), '"+roleList+"', '"+realName+"', '"+penName+"', '"+sexcode+"', '"+addDeptId+"', NULL,"
							 + "'"+displayOrder+"','"+dutyFlag+"','"+phone+"','"+kpJoin+"','"+kpPerson+"','"+dutyCode+"','"+dutyOthers+"','"+operCode+"',NOW(),'"+deptCode+"','"+groupCode+"',STR_TO_DATE('"+birth+"','%Y%m%d'),'"+range+"')"; //'"+taskNum+"', '"+kpClass+"',
					ps2= conn.prepareStatement(saveSql);	
					ps2.addBatch();
					if(dutyFlag.equals("1")){
						saveSql="update dept set duty_name='"+userName+"', duty_phone='"+phone+"' where dept_sts='A' and dept_id='"+addDeptId+"' ";
						ps3 = conn.prepareStatement(saveSql);
						ps3.addBatch();
						ps3.executeBatch();
					}
					
					//ps.executeBatch();
					ps2.executeBatch();
					conn.commit();
					jsobject.put("respCode", "0");
					jsobject.put("respDesc", "保存成功");
				}catch(Exception e){
					e.printStackTrace();
					 try{
						conn.rollback();
						jsobject.put("respCode", "-1");
						jsobject.put("respDesc", "保存失败");
					}catch(SQLException e1){
						e1.printStackTrace();
					}					
				}finally{
					try {
					  	if (ps != null) {
							ps.close();
						}
						if (ps2 != null) {
							ps2.close();
						}
						if (ps3 != null) {
							ps3.close();
						}
						if (conn != null) {
							conn.close();
						}
						if (session != null) {
							session.close();
						}

					} catch (Exception e) {
					}
					baseDAO.closeSession(session);
				}
			}else{
				jsobject.put("savetype", "edit");
				SqlSession session = null;
				Connection conn = null;
				PreparedStatement ps = null;
				PreparedStatement ps2 = null;
				PreparedStatement ps3 = null;
				try{
					session = baseDAO.getSession();
					conn = session.getConnection();
					conn.setAutoCommit(false);
					if(backUp.equals("true")){
						String pwdSql = "select password from USER_INFO t where user_id ='"+userId+"' and sts='A' ";
						JSONObject jso = baseDAO.findBySqlToJosn(pwdSql);
						JSONObject jso2 = jso.getJSONArray("list").getJSONObject(0);
						String pwd = jso2.getString("password");
						saveSql="update user_info SET sts='C',sts_date=NOW() where user_id ='"+userId+"' and sts='A' ";
						ps= conn.prepareStatement(saveSql);	
						ps.addBatch();
						saveSql= "insert into user_info "+
								 " (user_name, password,rank, sts, sts_date, role_list, real_name,another_name, user_id, sex_type,  cur_dept_id, oper_dept_id, "
								 + " display_order, duty_flag, phone, kp_join, kp_person, duty_code, duty_others, oper_code, oper_date, dept_code, group_code, birth,ps_range )" + //task_num, kp_class,
								 " values "+
								 " ('"+userName+"','"+pwd+"','"+rankcode+"', 'A', NOW(), '"+roleList+"', '"+realName+"','"+penName+"', '"+userId+"', '"+sexcode+"', '"+addDeptId+"', NULL,"  //'"+taskNum+"',  '"+kpClass+"',
								 + "'"+displayOrder+"','"+dutyFlag+"','"+phone+"','"+kpJoin+"','"+kpPerson+"','"+dutyCode+"','"+dutyOthers+"','"+operCode+"',NOW(),'"+deptCode+"','"+groupCode+"', STR_TO_DATE('"+birth+"','%Y%m%d'),'"+range+"')";
						ps2= conn.prepareStatement(saveSql);	
						ps2.addBatch();
						
						ps.executeBatch();
						ps2.executeBatch();
					}else{
						saveSql="update user_info "
							+" set user_name= '"+userName+"', "
							+" rank = '"+rankcode+"',"
							+"sts = 'A',"
							+"sts_date = NOW(),"
							+"role_list = '"+roleList+"',"
							+"real_name = '"+realName+"',"
							+"another_name='"+penName+"',"
							+"sex_type = '"+sexcode+"',"
							+"cur_dept_id = '"+addDeptId+"',"
							+"oper_dept_id = NULL,"
							+"display_order='"+displayOrder+"',"
							+"duty_flag='"+dutyFlag+"',"
							+"phone='"+phone+"',"
//							+"task_num='"+taskNum+"',"
							+"kp_join='"+kpJoin+"',"
							+"kp_person='"+kpPerson+"',"
							+"duty_code='"+dutyCode+"',"
							+"duty_others='"+dutyOthers+"',"
//							+"kp_class='"+kpClass+"',"
							+"oper_code='"+operCode+"',"
							+"oper_date=NOW(),"
							+"dept_code='"+deptCode+"',"
							+"group_code='"+groupCode+"', "
							+"birth=STR_TO_DATE('"+birth+"','%Y%m%d'),"
							+"ps_range='"+range+"' "
							+" where user_id = '"+userId+"' AND sts='A'";
						ps= conn.prepareStatement(saveSql);	
						ps.addBatch();
						ps.executeBatch();
					}
					if(dutyFlag.equals("1")){
						saveSql="UPDATE dept SET duty_name='"+userName+"',duty_phone='"+phone+"' where dept_id='"+addDeptId+"' and dept_sts='A'";
						ps3= conn.prepareStatement(saveSql);
						ps3.addBatch();
						ps3.executeBatch();
					}
					
					conn.commit();
					jsobject.put("respCode", "0");
					jsobject.put("respDesc", "保存成功");					
				}catch(Exception e){
					e.printStackTrace();
					 try{
						conn.rollback();
						jsobject.put("respCode", "-1");
						jsobject.put("respDesc", "保存失败");
					 }catch(SQLException e1){
						e1.printStackTrace();
					 }		
				}finally{
					try {
					  	if (ps != null) {
							ps.close();
						}
						if (ps2 != null) {
							ps2.close();
						}
						if (ps3 != null) {
							ps3.close();
						}
						if (conn != null) {
							conn.close();
						}
						if (session != null) {
							session.close();
						}

					} catch (Exception e) {
					}
					baseDAO.closeSession(session);
				}
				
			}
			
				jsobject.put("userName", userName);
				if (roleList.length() >= 3)
				{
					roleList = roleList.substring(1, roleList.length() - 1);
				}
				jsobject.put("roleList", roleList);
				System.out.println(roleList);
				jsobject.put("roleListName",userInfoService.getRoleListNames(roleList));
				jsobject.put("realName", realName);
				jsobject.put("penName", penName);
				jsobject.put("sexType", sexcode);
//				jsobject.put("sexTypeName", userInfoService.getSexName(sexcode));	
//				jsobject.put("deptName", userInfoService.getDeptName(addDeptId));
				jsobject.put("rank", rankcode);
				jsobject.put("userId", userId);	
				jsobject.put("operDeptId", operDeptId);
				jsobject.put("deptId",addDeptId);
				jsobject.put("operDeptName", operDeptName);
				jsobject.put("userName", userName);
				jsobject.put("displayOrder", displayOrder);
				jsobject.put("dutyFlag", dutyFlag);
				jsobject.put("phone", phone);
//				jsobject.put("taskNum", taskNum);
				jsobject.put("kpJoin", kpJoin);
				jsobject.put("kpPerson", kpPerson);
				jsobject.put("dutyCode", dutyCode);
//				jsobject.put("kpClass", kpClass);
				jsobject.put("deptCode", deptCode);
				jsobject.put("groupCode", groupCode);
				jsobject.put("birth", birth);
				jsobject.put("ps_range", range);
		}catch(Exception e){
			jsobject.put("respCode", "9");
			jsobject.put("respDesc", "系统错误");
			return jsobject.toString();
		}
		
		
		return jsobject.toString();
	}
    
    
    @RequestMapping("checkoldpasswd")
    @ResponseBody
    public String checkoldpasswd(HttpServletRequest req){
    	JSONObject jsobject = new JSONObject();
    	String userId = (String)req.getSession().getAttribute("userId");
    	String oldPwd = req.getParameter("oldPassWord");
    	String sql = "SELECT password FROM user_info WHERE user_id='"+userId+"' and sts='A'";
    	try {
    		String password="";
    		jsobject  =baseDAO.findBySqlToJosn(sql);
    		if ("0".equals(jsobject.getString("respCode"))) {
  	    	  JSONArray list = jsobject.getJSONArray("list");
  	    	  if(list.size()>0)
  	    	  {
  	    		   password=list.getJSONObject(0).getString("password");
  	    		  
	  	    		if(oldPwd.equals(password)){
	  					jsobject.put("respCode", "0");	  					
	  					jsobject.put("respDesc", "OK");
	  				}else{
	  					jsobject.put("respCode", "-1");	  				
	  					jsobject.put("respDesc", "原密码不正确");
	  				}	
	  	    	  }
  	    	  else
  	    	  {
  	    		jsobject.put("respCode", "-1");
  				jsobject.put("respDesc", "系统无该用户");		
  	    	  }
  	      }
			
			
					
		} catch (Exception e) {
			jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "系统错误");		
			
		}
    	log.info("checkoldpasswd "+jsobject.toString());
    	return jsobject.toString();
    }
    
    
    @RequestMapping("/userInfoPwdSave")
    @ResponseBody
    public String userInfoPwdSave(HttpServletRequest req){

    	JSONObject jsobject = new JSONObject();
    	String newPwd = req.getParameter("newPassWord");
    	String userId = (String)req.getSession().getAttribute("userId");
    	String sql= "Update user_info SET password='"+newPwd+"' WHERE user_id='"+userId+"'";
    	boolean result = baseDAO.excuteSql(sql, null);
    	if(result){
    		jsobject.put("respCode", "0");        		
    		jsobject.put("respDesc", "密码修改成功，请重新登录");
    	}else{
    		jsobject.put("respCode", "1");    	
    		jsobject.put("respDesc", "系统忙，请稍后再试");
    	}		
    	
    	log.info("userInfoPwdSave "+jsobject.toString());
    	return jsobject.toString();
    }
    
    @RequestMapping("/resetPwd")
    @ResponseBody
    public String resetPwd(HttpServletRequest req){
    	JSONObject jsobject = new JSONObject();
    	String userId = req.getParameter("userId");
 //   	String pwd = req.getParameter("pwd");
    	try{
    		String pwd= Md5Str.str2MD5to16byte(ToolsUtil.getProp("config.properties", "dft_pwd"));
	    	if(userId!=null&&!"".equals(userId)){
	    		String sql="UPDATE user_info SET password='"+pwd+"' WHERE user_id='"+userId+"' and sts='A'";
	    		if(baseDAO.excuteSql(sql,null)){
	    			jsobject.put("respCode", "0");
					jsobject.put("respDesc", "重置密码成功");
	    		}else{
	    			jsobject.put("respCode", "-1");
	    			jsobject.put("respDesc", "重置密码失败");
	    		}
	    	}else{
	    		jsobject.put("respCode", "-1");
				jsobject.put("respDesc", "重置密码失败");
	    	}    	
    	}
    	catch(Exception e){
    		jsobject.put("respCode", "-1");
			jsobject.put("respDesc", "重置密码失败");
    	}
    	log.info("resetPwd "+jsobject.toString());
    	return jsobject.toString();
    }
    
    
    /**
     * http://127.0.0.1:8080/ssm/pub/userInfo/deptUserTreeEx?id=0
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/deptUserTreeEx")
    @ResponseBody
	public String deptUserTreeEx(HttpServletRequest req)
	{
    	JSONObject result = new JSONObject();
    	HttpSession session = req.getSession();
    	String rankDeptId=(String)session.getAttribute("rankDeptId") == null ? "" : (String)session.getAttribute("rankDeptId");
    		
    	String showRang = "";    	
    	try{
    		showRang = ToolsUtil.getProp("config.properties", "showRang");    	
    	}catch(Exception e){
    		e.printStackTrace();
    		result.put("respCode", "999");
    		result.put("respDesc", "获取config数据失败");
    		return result.toString();
    	}
    	
    	String id="";
    	if("0".equals(showRang))
    	{
    		 id=req.getParameter("id"); 
    	}
    	else if ("2".equals(showRang))
    	{
    		 id=rankDeptId; 
    	}
    	else if ("1".equals(showRang))
    	{
    		//到底以谁为主看需求
    		id=rankDeptId; 
    	}    	
    	
    	//前台deptId=1;
    	
        //构造当前部门节点
    	JSONArray array = new JSONArray();
    	JSONObject jsobject = new JSONObject();		
    	jsobject=userInfoService.getDeptUserInfo(id);
    	if ("0".equals(jsobject.getString("respCode"))&&jsobject.getJSONArray("list").size()>0) {
    		
    		JSONObject obj = new JSONObject();    	
    			obj.put("id", jsobject.getJSONArray("list").getJSONObject(0).getString("id"));
				obj.put("pid", jsobject.getJSONArray("list").getJSONObject(0).getString("pid"));
				if(jsobject.getJSONArray("list").getJSONObject(0).getString("data_sign").equals("p"))
				{
				     obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("label")+"👱");
				}
				else
				{
					 obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("label")+"");
				}
				obj.put("data_sign", jsobject.getJSONArray("list").getJSONObject(0).getString("data_sign"));
				JSONArray jsonarray=userInfoService.loadTree(id);				
				if(jsonarray.size()>0)
				{
					obj.put("children", jsonarray);
				}
//				obj.put("id", jsobject.getJSONArray("list").getJSONObject(0).getString("id"));					
//				obj.put("pid", jsobject.getJSONArray("list").getJSONObject(0).getString("pid"));
//				if(jsobject.getJSONArray("list").getJSONObject(0).getString("data_sign").equals("p"))
//				{
//					obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("label")+"👱");
//				}
//				else
//				{
//					obj.put("label", jsobject.getJSONArray("list").getJSONObject(0).getString("label")+"");
//				}
//				obj.put("data_sign", jsobject.getJSONArray("list").getJSONObject(0).getString("data_sign"));
	    	
				array.add(obj);       		
    		result.put("tree", array);
    		result.put("respCode", "0");
    		result.put("respDesc", "OK");
    		
    	}else{
    		result.put("respCode", "-1");
    		result.put("respDesc", "访问"+id+"部门信息失败");
    		
    	}    	
    	
    	log.info("deptUserTreeEx "+result.toString());
    	
		return result.toString();
	}
    
    /**
     * http://127.0.0.1:8080/ssm/pub/userInfo/importUsers
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/importUsers")
    @ResponseBody
	public String importUsers(HttpServletRequest req){
    	JSONObject result = new JSONObject();
    	String root = req.getServletContext().getRealPath("/");
    	String path = req.getParameter("path")==null?"":req.getParameter("path");
    	String deptId = req.getParameter("deptId")==null?"1":req.getParameter("deptId");
    	JSONObject jsdata = new JSONObject();
    	jsdata.put("oper_code", (String)req.getSession().getAttribute("userId"));
		jsdata.put("filePath", root+File.separator+path);
    	jsdata.put("dept_id", deptId);
		result = userInfoService.importUsers(jsdata);
    	log.info("importUsers "+result.toString());
    	return result.toString();
	}
    
    
    
    
    /**
	 * 用户删除
	 * 
	 * @description：
	 * @author LIU CHANG
	 * 
	 * 
	 * @createDate 2018-3-26
	 * @createTime 下午12:06:44
	 */
    @RequestMapping("/userInfoDel")
    @ResponseBody
    public String userInfoDel(HttpServletRequest req)
	{
		JSONObject jsobject = new JSONObject();
		String userId = req.getParameter("userId");
		jsobject = userInfoService.delUser(userId);
		return jsobject.toString();
	}
    
    
}
